package com.yjd.comm.base.concurrent.task;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 默认任务处理器
 * 
 * @author ready
 * @date 2014-8-8
 */
public class DefaultTaskDispose implements ITaskDispose {

	/**
	 * 是否支持多线程
	 */
	private boolean moreThread;
	/**
	 * 线程池大小
	 */
	private int poolSize;

	/**
	 * poolsize所在const.properties文件中的key
	 */
	private String poolSizePropertiesKey;

	public DefaultTaskDispose() {
	}

	public DefaultTaskDispose(boolean moreThread, int poolSize) {
		this.moreThread = moreThread;
		this.poolSize = poolSize;
	}

	/**
	 * 任务处理，支持多线程并发处理
	 * 
	 * @param taskItems
	 *            任务列表
	 * @param taskHandler
	 *            任务处理器
	 * @throws InterruptedException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void taskDipose(List taskItems, ITaskHandler taskHandler)
			throws Exception {
		List<ITaskItem> list = taskItems;
		if (this.isMoreThread()) {
			ScheduledExecutorService pool = Executors
					.newScheduledThreadPool(this.getPoolSize());
			CountDownLatch countDownLatch = new CountDownLatch(taskItems.size());
			for (ITaskItem taskItem : list) {
				pool.execute(new TaskDisposer(countDownLatch, taskHandler,
						taskItem));
			}
			countDownLatch.await();
			pool.shutdown();
		} else {
			for (ITaskItem taskItem : list) {
				taskHandler.dispose(taskItem);
			}
		}
	}

	public String getPoolSizePropertiesKey() {
		return poolSizePropertiesKey;
	}

	public void setPoolSizePropertiesKey(String poolSizePropertiesKey) {
		this.poolSizePropertiesKey = poolSizePropertiesKey;
	}

	public boolean isMoreThread() {
		return moreThread;
	}

	public void setMoreThread(boolean moreThread) {
		this.moreThread = moreThread;
	}

	public int getPoolSize() {
		return poolSize;
	}

	public void setPoolSize(int poolSize) {
		this.poolSize = poolSize;
	}
}
